package com.samsung.controller.lots;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.samsung.common.annotation.LoginAjaxAuth;
import com.samsung.common.annotation.LoginAuth;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;
import com.samsung.dto.common.JErrorResult;
import com.samsung.dto.common.JSuccResult;
import com.samsung.dto.lots.GroupingLotsDto;
import com.samsung.model.common.Page;
import com.samsung.model.lots.LotsCandidate;
import com.samsung.model.lots.LotsEvent;
import com.samsung.model.lots.LotsItem;
import com.samsung.model.lots.LotsRecord;
import com.samsung.model.user.User;
import com.samsung.service.lots.LotsService;
import com.samsung.service.user.UserService;

/**
 * 
 * @Title: LotsController.java 
 * @Package com.samsung.controller.lots 
 * @Description: 抽签控制器
 * @author  minhai.hui  
 * @date 2015年5月13日 下午3:46:03 
 * @version V1.0
 */

@Controller
@RequestMapping("/lots")
public class LotsController {
	@Autowired
	private LotsService lotsService;
	
	@Autowired
	private UserService userService;
	
	
	
	/**
	 * 投票列表
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView voteList() {
		return new ModelAndView("lots/list");
	}
	
	/**
	 * 抽签列表页面
	 * @param search_title
	 * @param createTime
	 * @param currentPage
	 * @param request
	 * @throws Exception
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Map<String, Object> getLotsList(String search_title,String createTime,Integer currentPage,Map<String, Object> model, HttpServletRequest request,HttpSession session) {
		
		Map<String, Object> condition =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		String ip = BaseUtil.getRemoteHost(request);
		
		condition.put("ip", ip);
		condition.put("uid", user.getUid());
		condition.put("search_title", search_title);
		condition.put("createTime", createTime);
		
		int totalCount=lotsService.getTotalCount(condition);
		
		Page page = new Page(totalCount, currentPage);
		condition.put("page", page);
		List<Map<String, Object>> resultMap = lotsService.getLotsList(condition);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("resultMap", resultMap);
		reMap.put("page", page);
		return reMap;
		
	}
	
	/**
	 * 跳转抽签活动创建页面
	 * @return
	 */
	@LoginAuth
	@RequestMapping("/create")
	public ModelAndView createLotsPage(){
		return new ModelAndView("lots/create");
	}	
	
	/**
	 * 保存抽签活动信息
	 * @param lotsEvent
	 * @param candidatesId
	 * @param itemsTitle
	 * @param session
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Object saveLots(LotsEvent lotsEvent, String candidatesId, String itemsTitle, HttpSession session){
		//根据抽签类型跳转页面，1抽奖式，2分组式
		Map<String, String> map=new HashMap<String, String>();
		User user=(User) session.getAttribute(Constant.LOGIN_TOKEN);
		lotsEvent.setUid(user.getUid());
		//此处有待完善，抽签开始的时间应该是结果保存的时间点，amount字段可扩展
		lotsEvent.setCreateTime(new Date());
		lotsEvent.setStartTime(new Date());
		if (lotsEvent.getType()==1) {
			lotsEvent.setAmount(1);
			lotsService.addLots(lotsEvent, candidatesId, itemsTitle);
			map.put("type", "1");
		} else {
			lotsService.addLots(lotsEvent, candidatesId, itemsTitle);
			map.put("type", "2");
		}
		map.put("lid", lotsEvent.getId());
		return map;
	}
	

	/**
	 * 分组业务方法
	 * @param candidateList
	 * @param groupList
	 * @return
	 */
	private List<GroupingLotsDto> avgGrouping(List<LotsCandidate> candidateList, List<LotsItem> groupList){
		List<GroupingLotsDto> result = new ArrayList<GroupingLotsDto>();
		
		for (int i = 0; i < groupList.size(); i++) {
			if(candidateList.size() <= 0) {
				break;
			}
			
			int randIndex = (int) (Math.random() * candidateList.size());
			
			User user = userService.selectByPrimaryKey(candidateList.get(randIndex).getUid());
			GroupingLotsDto groupingLotsDto = new GroupingLotsDto();
			groupingLotsDto.setItem(groupList.get(i));
			groupingLotsDto.setUser(user);
			
			result.add(groupingLotsDto);
			candidateList.remove(randIndex);
			
			if(i == (groupList.size()-1)) {
				i = -1;
			}
		}
			
		return result;
	}
	
	/**
	 * 分组抽签页面
	 * @param lid
	 * @return
	 * @throws IOException 
	 */
	@LoginAuth
	@RequestMapping("/grouping")
	public ModelAndView groupingLots(String lid) throws IOException{
		ModelAndView mav = new ModelAndView();
		//获得分组结果
		List<LotsCandidate> candidate = lotsService.getCandidate(lid);
		List<LotsItem> item = lotsService.listLotsItem(lid);
		
		List<GroupingLotsDto> result = null;
		int cnt = lotsService.getRecordCount(lid);
		if(cnt <= 0){ //未分组
			//随机平均分组
			result = avgGrouping(candidate, item);
			//将结果存入数据库
			insertLotsRecord(result);
		} else {
			result = new ArrayList<GroupingLotsDto>();
			List<LotsRecord> lotsRecord = lotsService.getLotsRecordByLid(lid);
			for(LotsRecord lr:lotsRecord){
				GroupingLotsDto groupingLotsDto = new GroupingLotsDto();
				groupingLotsDto.setUser(userService.selectByPrimaryKey(lr.getUid()));
				groupingLotsDto.setItem(lotsService.selectByPrimaryKey(lr.getIid()));
				
				result.add(groupingLotsDto);
			}
		}

		mav.addObject("result", result);
		mav.setViewName("lots/grouping");
		return mav;
	}
	
	/**
	 * 简易分页画面
	 * @param lid
	 * @return
	 * @throws Exception
	 */
	@LoginAuth
	@RequestMapping("/simple")
	public ModelAndView simpleLotsPage(String lid) throws Exception {
		ModelAndView mav = new ModelAndView();
		List<LotsCandidate> candidateList = lotsService.getCandidate(lid);
		LotsEvent event = lotsService.selectLotsEventByPrimaryKey(lid);
		LotsRecord record = lotsService.getLotsRecord(lid);
		if(record!=null){
			mav.addObject("record",record);
		}
		mav.addObject("candidateList", candidateList);
		mav.addObject("lotsEvent", event);
		mav.setViewName("lots/simple");
		
		return mav;
	}
	
	/**
	 * 抽签结果保存功能
	 * @param name
	 * @param lid
	 * @return
	 * @throws Exception
	 */
	@LoginAjaxAuth
	@ResponseBody
	@RequestMapping("/record/save")
	public Map<String, Object> saveRecords(String name,String lid) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		LotsRecord  record=new LotsRecord();
		record.setUid(name);
		int cnt=lotsService.insetLotsRecord(record,lid);
		if(cnt==1){
			resultMap.put("success", true);
			resultMap.put("msg", "保存成功");
		}else{
			resultMap.put("success", false);
			resultMap.put("msg", "保存失败");
		}
		
		return resultMap;
	}
	
	/**
	 * 保存抽签结果
	 * @param result
	 * @return
	 */
	private void insertLotsRecord(List<GroupingLotsDto> result){
		LotsRecord  lr = new LotsRecord();
		try {
			for(GroupingLotsDto gld:result){
				lr.setId(BaseUtil.getUUID());
				lr.setIid(gld.getItem().getId());
				lr.setStartTime(new Date());
				lr.setCreateTime(new Date());
				lr.setUid(gld.getUser().getUid());
				lr.setLid(gld.getItem().getLid());
				
				lotsService.insetLotsRecord(lr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除抽签
	 * @param lotId
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@LoginAjaxAuth
	@ResponseBody
	@RequestMapping("/delete")
	public Object delete(String lid, HttpSession session) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		LotsEvent event = lotsService.selectLotsEventByPrimaryKey(lid);
		if(event == null) {
			resultMap.put("success", false);
			resultMap.put("msg", "抽签活动不存在");
			return resultMap;
		}
		
		User sessUser = (User) session.getAttribute(Constant.LOGIN_TOKEN);
		if(!sessUser.getUid().equalsIgnoreCase(event.getUid())) {
			resultMap.put("success", false);
			resultMap.put("msg", "您只能删除自己创建的活动");
			return resultMap;
		}
		
		int cnt=lotsService.delete(lid);
		if(cnt > 0) {
			return new JSuccResult("删除成功");
		}
		
		return new JErrorResult("删除失败");
	}
	
}
